package test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class Demo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("do post");

        String account = req.getParameter("account");
        String password = req.getParameter("password");
        System.out.println(account+password);

        resp.setContentType("text/plain;charset=utf8");
        //设置回去的内容
        resp.setCharacterEncoding("utf-8");
        if (ways(account,password)){
            req.getRequestDispatcher("success.html").forward(req,resp);
        }else{
            req.getRequestDispatcher("error.html").forward(req,resp);

        }
    }

    private boolean ways(String account, String password) {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url="jdbc:mysql://localhost:3306/demotest01 ?characterEncoding=UTF-8&serverTimezone=GMT%2B8";
            String mysqluser="root";
            String mysqlpasd="root";
            Connection connection = DriverManager.getConnection
                    (url, mysqluser, mysqlpasd);

            Statement statement = connection.createStatement();
            String sql="select * from user where account='"+account+"',and password='"+password+"'";
            ResultSet resultSet = statement.executeQuery(sql);
            boolean ok = resultSet.next();

            resultSet.close();
            statement.close();
            connection.close();
            return ok;



        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
            return true;
    }
}
